<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="queryParams.userId" placeholder="请输入用户ID或昵称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="订单号" prop="orderNo">
            <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="订单状态" prop="orderStatus">
            <el-select v-model="queryParams.orderStatus" placeholder="请选择" clearable style="width: 120px">
              <el-option label="等待支付" value="1" />
              <el-option label="等待发货" value="2" />
              <el-option label="确认收货" value="3" />
              <el-option label="等待评论" value="4" />
              <el-option label="售后" value="5" />
              <el-option label="订单完成" value="6" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['mall:orders:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mall:orders:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mall:orders:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mall:orders:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" align="center" type="index" />
        <el-table-column label="订单图片" align="center" prop="orderImage" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.orderImage" :width="30" :height="30" />
          </template>
        </el-table-column>
        <el-table-column label="订单号" align="center" prop="orderNo" width="180" />
        <el-table-column label="会员ID" align="center" prop="userId" />
        <el-table-column label="订单号" align="center" prop="orderNo" width="180" />
        <el-table-column label="总支付金额" align="center" prop="totalPrice" />
        <el-table-column label="订单状态" align="center" prop="orderStatus" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.orderStatus === 0" type="danger">取消</el-tag>
            <el-tag v-else-if="row.orderStatus === 1" type="primary">等待支付</el-tag>
            <el-tag v-else-if="row.orderStatus === 2" type="info">等待发货</el-tag>
            <el-tag v-else-if="row.orderStatus === 3" type="primary">确认收货</el-tag>
            <el-tag v-else-if="row.orderStatus === 4" type="success">等待评论</el-tag>
            <el-tag v-else-if="row.orderStatus === 5" type="warning">售后</el-tag>
            <el-tag v-else-if="row.orderStatus === 6" type="success">订单完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="" align="center" prop="updateDept" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['mall:orders:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['mall:orders:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改全部订单对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="ordersFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="优惠券日志ID" prop="couponId">
          <el-input v-model="form.couponId" placeholder="请输入优惠券日志ID" />
        </el-form-item>
        <el-form-item label="拼团日志ID" prop="collectiveId">
          <el-input v-model="form.collectiveId" placeholder="请输入拼团日志ID" />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="订单标题" prop="orderName">
          <el-input v-model="form.orderName" placeholder="请输入订单标题" />
        </el-form-item>
        <el-form-item label="订单图片" prop="orderImage">
          <image-upload v-model="form.orderImage" />
        </el-form-item>
        <el-form-item label="总支付金额" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入总支付金额" />
        </el-form-item>
        <el-form-item label="订单计算金额" prop="orderPrice">
          <el-input v-model="form.orderPrice" placeholder="请输入订单计算金额" />
        </el-form-item>
        <el-form-item label="余额支付金额" prop="orderBalance">
          <el-input v-model="form.orderBalance" placeholder="请输入余额支付金额" />
        </el-form-item>
        <el-form-item label="运费金额" prop="freightMoney">
          <el-input v-model="form.freightMoney" placeholder="请输入运费金额" />
        </el-form-item>
        <el-form-item label="优惠金额" prop="couponMoney">
          <el-input v-model="form.couponMoney" placeholder="请输入优惠金额" />
        </el-form-item>
        <el-form-item label="是否结算" prop="isSettlement">
          <el-input v-model="form.isSettlement" placeholder="请输入是否结算" />
        </el-form-item>
        <el-form-item label="快递订单号" prop="deliveryNo">
          <el-input v-model="form.deliveryNo" placeholder="请输入快递订单号" />
        </el-form-item>
        <el-form-item label="快递公司编码" prop="deliveryCode">
          <el-input v-model="form.deliveryCode" placeholder="请输入快递公司编码" />
        </el-form-item>
        <el-form-item label="收件人名" prop="receiveName">
          <el-input v-model="form.receiveName" placeholder="请输入收件人名" />
        </el-form-item>
        <el-form-item label="收件人手机" prop="receiveTel">
          <el-input v-model="form.receiveTel" placeholder="请输入收件人手机" />
        </el-form-item>
        <el-form-item label="地址信息" prop="receiveArea">
          <el-input v-model="form.receiveArea" placeholder="请输入地址信息" />
        </el-form-item>
        <el-form-item label="详细地址信息" prop="receiveAddress">
          <el-input v-model="form.receiveAddress" placeholder="请输入详细地址信息" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentName">
          <el-input v-model="form.paymentName" placeholder="请输入支付方式" />
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker v-model="form.payTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择支付时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发货时间" prop="deliveryTime">
          <el-date-picker v-model="form.deliveryTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="确认收货时间" prop="receiptTime">
          <el-date-picker v-model="form.receiptTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择确认收货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="评论时间" prop="commentTime">
          <el-date-picker v-model="form.commentTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择评论时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="" prop="updateDept">
          <el-input v-model="form.updateDept" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Orders" lang="ts">
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from '@/api/mall/orders';
import { OrdersVO, OrdersQuery, OrdersForm } from '@/api/mall/orders/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const ordersList = ref<OrdersVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const ordersFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrdersForm = {
  id: undefined,
  userId: undefined,
  couponId: undefined,
  collectiveId: undefined,
  orderNo: undefined,
  orderName: undefined,
  orderImage: undefined,
  totalPrice: undefined,
  orderPrice: undefined,
  orderBalance: undefined,
  freightMoney: undefined,
  couponMoney: undefined,
  orderStatus: undefined,
  refundStatus: undefined,
  isSettlement: undefined,
  deliveryNo: undefined,
  deliveryCode: undefined,
  receiveName: undefined,
  receiveTel: undefined,
  receiveArea: undefined,
  receiveAddress: undefined,
  paymentName: undefined,
  payTime: undefined,
  deliveryTime: undefined,
  receiptTime: undefined,
  commentTime: undefined,
  remark: undefined,
  updateDept: undefined
};
const data = reactive<PageData<OrdersForm, OrdersQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    orderStatus: undefined,
    orderNo: undefined,
    orderName: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
    orderNo: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
    orderName: [{ required: true, message: '订单标题不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询全部订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrders(queryParams.value);
  ordersList.value = res.rows;
  console.log(res);
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  ordersFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrdersVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加全部订单';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: OrdersVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getOrders(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改全部订单';
};

/** 提交按钮 */
const submitForm = () => {
  ordersFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateOrders(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addOrders(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: OrdersVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除全部订单编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delOrders(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'mall/orders/export',
    {
      ...queryParams.value
    },
    `orders_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
